package xyz.quanguanjia.masterboy;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.util.Timer;
import java.util.TimerTask;

import xyz.quanguanjia.masterboy.model.MBDAccountInfoModel;

public class MBDUserCenter {

    private static MBDUserCenter instance = new MBDUserCenter();
    private MBDUserCenter(){}
    //获取唯一可用的对象
    public static MBDUserCenter shared(){
        return instance;
    }

    public  boolean userInfoFetched(){
        if (TextUtils.isEmpty(this.getToken())) {
            return false;
        }

        MBDAccountInfoModel infoModel = MBDAccountInfoModel.current();
        if (null != infoModel && null != infoModel.getUserId()) {

            return true;
        }
        return false;
    }

    public void setToken(String token){

        if (token == null || token.length() < 1) {
            SharedPreferences sharedPreferences = MBDApplication.getContext().getSharedPreferences("login_info", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            MBDAccountInfoModel.clear();
            editor.clear();
            editor.apply();
        } else {
            SharedPreferences sharedPreferences = MBDApplication.getContext().getSharedPreferences("login_info", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("token", token);
            editor.apply();

            //拉取用户信息
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 在此处执行函数
                    MBDAccountInfoModel.fetch();
                }
            }, 1500);

        }
    }

    public String getToken(){

        SharedPreferences sharedPreferences = MBDApplication.getContext().getSharedPreferences("login_info", Context.MODE_PRIVATE);
        return sharedPreferences.getString("token","");
    }

}
